package com.fly.web;

import com.fly.base.Result;
import com.fly.base.ResultGenerator;
import com.fly.domain.model.Customer;
import com.fly.domain.model.CustomerCashInfo;
import com.fly.domain.service.CustomerCashInfoService;
import com.fly.domain.service.CustomerService;
import com.fly.util.SidService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * Created by frinder on 2018/4/8.
 */
@RestController
@RequestMapping("/myCustomerCashInfo")
public class MyCustomerCashInfoController {

    @Autowired
    private CustomerService customerService;

    @Resource
    private CustomerCashInfoService customerCashInfoService;

    @Autowired
    private SidService sidService;

    @PostMapping("/add")
    public Result add(CustomerCashInfo customerCashInfo) {
        Optional.ofNullable(customerService.findBy("sid", customerCashInfo.getCustomerSid()))
                .ifPresent(s -> {
                    customerCashInfo.setSid(sidService.getSid(SidService.Biz.CUSTOMER));
                    customerCashInfo.setCustomerName(s.getName());
                    customerCashInfo.setBeforeCash(s.getCash());
                    double afterCash = customerCashInfo.getCash() + customerCashInfo.getBeforeCash();
                    afterCash = afterCash > 0 ? afterCash : 0;
                    customerCashInfo.setAfterCash(afterCash);
                    customerCashInfoService.save(customerCashInfo);
                    //
                    Customer updateCustomer = new Customer();
                    updateCustomer.setId(s.getId());
                    updateCustomer.setCash(customerCashInfo.getAfterCash());
                    customerService.update(updateCustomer);
                });
        return ResultGenerator.genSuccessResult();
    }

}
